package org.assistant.csp.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.assistant.csp.data.Global;

public final class LoginFilter implements Filter {
	protected final static Log log = LogFactory.getLog(LoginFilter.class);
	private static boolean isDebugEnabled = log.isDebugEnabled();

	@SuppressWarnings("unused")
	private static ServletContext servletContext = null;

	private static final String LOGIN_PAGE = "/hcm/login.t?m=index";
	private List<String> noCheck = null;

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		if (req.getCharacterEncoding() == null) {
			req.setCharacterEncoding("UTF-8");
		}
		try {
			HttpServletRequest hreq = (HttpServletRequest) req;
			if (noCheck == null) {
				noCheck = new ArrayList<String>();
				String contextPath = hreq.getContextPath();
				if (isDebugEnabled) {
					log.debug("contextPath:" + contextPath);
				}
				noCheck.add(contextPath + "/");
				noCheck.add(contextPath + "/index.html");
				noCheck.add(contextPath + "/hcm/login.t");
			}

			boolean isPassed = isPassed(hreq);

			if (isDebugEnabled) {
				log.debug("URI:" + hreq.getRequestURI());
				log.debug("isPassed:" + isPassed);
			}

			if (!isPassed) {
				((HttpServletResponse) resp).sendRedirect(hreq.getContextPath()
						+ LOGIN_PAGE);
				return;
			}
			chain.doFilter(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		servletContext = filterConfig.getServletContext();
	}

	private boolean isPassed(HttpServletRequest req) {
		if (noCheck.contains(req.getRequestURI())) {
			return true;
		} else if (req.getSession().getAttribute(Global.CURRENT_USER) == null) {
			return false;
		} else {
			return true;
		}
	}

}
